/**
 * @description 题目1
 */
class People {
  constructor(name) {
    this.name = name;
    this.events = {};
  }

  // 监听事件
  on(event, callback) {
    if (this.events[event]) {
      this.events[event].push(callback);
    } else {
      this.events[event] = [callback];
    }
  }

  // 解绑事件
  off(event, callback) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(
        (item) => item !== callback
      ); // [Function: say1], [Function: say2] 引用不同
    }
  }

  // 触发事件
  emit(event, ...args) {
    if (this.events[event]) {
      this.events[event].forEach((callback) => callback(...args));
    }
  }

  sayHi() {
    console.log(`Hi, I am ${this.name}`);
  }
}

/* 以下为测试代码 */
const say1 = (greeting) => {
  console.log(`${greeting}, nice meeting you.`);
};

const say2 = (greeting) => {
  console.log(`${greeting}, nice meeting you, too.`);
};

const jerry = new People("Jerry");
jerry.sayHi();
// => 输出：'Hi, I am Jerry'

jerry.on("greeting", say1);
jerry.on("greeting", say2);

jerry.emit("greeting", "Hi");
// => 输出：'Hi, nice meeting you.' 和 'Hi, nice meeting you, too'

jerry.off("greeting", say1);
jerry.emit("greeting", "Hi");
// => 只输出：'Hi, nice meeting you, too'

/**
 * @description 题目2
 */
const sleep = (duration) => {
  // 使用Promise 实现 sleep 功能
  return new Promise((resolve) => {
    setTimeout(resolve, duration);
  });
};

const anyFunc = async () => {
  console.log("123"); // 输出 123
  await sleep(300); // 暂停 300 毫秒
  console.log("456"); // 输出 456，但是距离上面输出的 123 时间上相隔了 300 毫秒
};
// anyFunc();

/**
 * @description 题目3
 */
const deepGet = (obj, prop) => {
  
  /// a[0].b -> a.0.b -> ['a', '0', 'b']
  const keyList = prop.replace(/\[(\d+)\]/g, '.$1').split('.')
 
  const result = keyList.reduce((prev, key) => {
      return Object(prev)[key]; 
  }, obj)
  return result === undefined ? undefined : result;
};

/** 以下为测试代码 */
deepGet({
  school: {
    student: { name: 'Tomy' },
  },
}, 'school.student.name') // => 'Tomy'

deepGet({
  school: {
    students: [
      { name: 'Tomy' },
      { name: 'Lucy' },
    ],
  }
}, 'school.students[1].name') // => 'Lucy'

// 对于不存在的属性，返回 undefined
deepGet({ user: { name: 'Tomy' } }, 'user.age') // => undefined
deepGet({ user: { name: 'Tomy' } }, 'school.user.age') // => undefined

/**
 * @description 题目4
 */
const combo = (...args) => {
  // 实现复合函数
  return (x) => {
    return args.reduceRight((res, cb) => {
      //从右往左执行
      return cb(res);
    }, x);
  };
};

/* 以下为测试代码 */
const addOne = (a) => a + 1;
const multiTwo = (a) => a * 2;
const divThree = (a) => a / 3;
const toString = (a) => a + "";
const split = (a) => a.split("");

split(toString(addOne(multiTwo(divThree(666)))));
// => ["4", "4", "5"]

const testForCombo = combo(split, toString, addOne, multiTwo, divThree);
testForCombo(666);
// => ["4", "4", "5"]


/**
 * @description 题目5
 */

/**
 * 先手有必胜策略:
 * 先手开始拿7个球里面的2个球,两个盘子剩下5个球和5个球
 * 
 */

